package com.xuyiwei.mayi.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Created by xuyiwei on 2019/4/23.
 */
public class ZookeeperDemo {
    //连接地址
    private static final String ADDRES = "127.0.0.1:2181";
    //session 会话
    private static final int SESSION_OUTTIME = 2000;
    //信号量,阻塞程序执行,用户等待zookeeper连接成功,发送成功信号，
    private static final CountDownLatch countDownLatch = new CountDownLatch(1);


    /**
     * 判断指定节点是否存在
     *
     * @param path
     *            节点路径
     */
    public Stat exists(String path, boolean needWatch,ZooKeeper zooKeeper) {
        try {
            return zooKeeper.exists(path, needWatch);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        ZookeeperDemo zookeeperDemo = new ZookeeperDemo();
        //这个是监听连接的，不能监听节点
        ZooKeeper zk = new ZooKeeper(ADDRES, SESSION_OUTTIME, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Event.EventType eventType = event.getType();
                Event.KeeperState state = event.getState();
                String path = event.getPath();
                if(Event.KeeperState.SyncConnected == state){
                    if(Event.EventType.None == eventType){
                        System.out.println("-------------------------zookeeper连接已经建立");
                        countDownLatch.countDown();
                    }else if (Event.EventType.NodeCreated == eventType) {
                        System.out.println( "-------------------------事件通知,新增node节点" + path);
                    } else if (Event.EventType.NodeDataChanged == eventType) {
                        System.out.println(  "-------------------------事件通知,当前node节点" + path + "被修改....");
                    }else if (Event.EventType.NodeChildrenChanged == eventType) {
                        System.out.println(  "-------------------------事件通知,当前node子节点" + path + "被修改....");
                    }

                }
            }
        });
        //如果想要在连接之后才去做别的操作  需要用到并罚保countDownLatch
        countDownLatch.await();
//        zookeeperDemo.exists("/itmayeidu_Lasting",true,zk);
        zk.getChildren("/itmayeidu_Lasting",true);

        zk.setData("/itmayeidu_Lasting/vbaa", "aaaa".getBytes(), -1);

        Thread.sleep(5000);
        zk.close();

    }
}
